package eclipse;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

//二分法查找
//[1, 8, 9, 18, 27, 48, 54, 56, 63, 64, 90]
public class ArrayExercise08 {
    public static void main(String[] args) {
        int[] arr = myRandomArray();
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println("查找的目标值:");
        int index = binarySearch(arr, new Scanner(System.in).nextInt());
        System.out.println(index);
    }

    private static int binarySearch(int[] arr,int target) {
        int lo = 0;
        int hi = arr.length - 1;
        int mid;
        while(true){
            if(lo <= hi){
                mid = (lo + hi) / 2;
                if(arr[mid] > target){
                    hi = mid - 1;
                }else if(arr[mid] < target){
                    lo = mid + 1;
                }else{
                    return mid;
                }
            }else{
                return -1;
            }
        }


    }

    private static int[] myRandomArray() {
        int len = 5 + new Random().nextInt(6);
        int arr[] = new int[len];
        for(int i = 0; i < arr.length; i++){
            arr[i] = new Random().nextInt(100);
        }
        return arr;
    }
}
